import React, { useEffect, useRef, useState } from 'react';
import { Form, Select, Input, Button, Space, Tabs, Divider, Popconfirm, } from 'antd';
import {
    DoubleRightOutlined,
    RedditOutlined,
    RightOutlined,
    FormOutlined,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    SaveOutlined,
    CloseCircleOutlined
} from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { Resizable } from 'react-resizable';
import { APP_STATUS, PLAYER_STATUS } from '@/common/constant'
import { State } from '@/apps/panel/reducers';
import {
    updateSelectedCommand,
    toggleCommentOnSelectedCommand,
    startInspecting,
    stopInspecting
} from '@/apps/panel/actions'
import {
    availableCommands,
    canCommandSelect,
    canCommandFind,
    doesCommandSupportTargetOptions,
    commandText
} from '@/common/command'
import ChatbotPanel from './ChatbotPanel'
import './index.less';
import { askBg, askPlayTab } from '@/common/ipc/ipc';
const { useForm } = Form
const RightResizable: any = Resizable

interface HandleProps {
    handleAxis: string;
    [key: string]: any;
}

const ResizeHandle = React.forwardRef<HTMLDivElement, HandleProps>((props, ref) => {
    const { handleAxis, ...restProps } = props;
    return <div ref={ref} className={`right-sidebar-resize-handle handle-${handleAxis}`} {...restProps} />;
});

const clearSelection = () => {
    if (window.getSelection) {
        const selection = window.getSelection();
        if (selection) {
            if (selection.empty) {  // 在 Chrome 浏览器清空误选的文本
                selection.empty();
            } else if (selection.removeAllRanges) {  // 在 Firefox 浏览器下清空误选的文本
                selection.removeAllRanges();
            }
        }
    }
}

// 侧边栏
export default function RightSidebar() {


    const ref = useRef(null)
    const [width, setWidth] = useState<number>(300);
    const [isExpanded, setIsExpanded] = useState<boolean>(false);
    const [tabKey, setTabKey] = useState<string>('');

    // 缓存宽度
    useEffect(() => {
        const rightSideWidth = window.localStorage.getItem('rightSideWidth')
        if (rightSideWidth) {
            setWidth(parseFloat(rightSideWidth))
        }
    }, [])

    const handleUnExpanded = () => {
        setIsExpanded(false)
        setTabKey('')
    }

    return (
        <RightResizable
            ref={ref}
            width={isExpanded ? width : 32}
            height={window.innerHeight}
            onResize={(e: any, { size }: any) => {
                setWidth(size.width);
            }}
            onResizeStop={(e: any, { size }: any) => {
                window.localStorage.setItem('rightSideWidth', String(size.width))
            }}
            handle={<ResizeHandle handleAxis="right" />}
            axis="x"
            minConstraints={[260, 0]}
            maxConstraints={[800, 0]}
            draggableOpts={{
                onMouseDown: (e: any) => {
                    // 解决在 Windows 操作系统下，Edge 浏览器 和 Chrome 浏览器，松开鼠标按键，依然能拖动
                    clearSelection();
                }
            }}
            resizeHandles={['w']}
        >
            <div className="fields-wrapper" style={{ width: isExpanded ? width : 32 }}>
                <Tabs
                    className='right-sidebar-tabs'
                    activeKey={tabKey}
                    tabPosition='right'
                    items={[{
                        label: <FormOutlined />,
                        key: 'editForm',
                        children: <EditorPanel onUnExpanded={handleUnExpanded} />
                    },
                    {
                        label: <RedditOutlined />,
                        key: 'playground',
                        children: <ChatbotPanel onUnExpanded={handleUnExpanded} />
                    }
                    ]}
                    onChange={(key) => {
                        setIsExpanded(true)
                        setTabKey(key)
                    }}
                />
            </div>
        </RightResizable>
    );
};

function OptionEditor(props: any) {
    const { label, onOk, onDelete } = props;
    const [editing, setEditing] = useState<boolean>(false)
    let newLabel = label
    return <div
        style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
        }}
    >
        <div style={{
            flex: 1,
            overflow: 'hidden',
        }}>
            {
                editing ? (
                    <Input
                        placeholder='请输入'
                        defaultValue={newLabel}
                        onBlur={() => setEditing(false)}
                        onPressEnter={() => setEditing(false)}
                        autoFocus
                        onChange={e => {
                            newLabel = e.target.value
                        }}
                        onClick={(e) => {
                            e.stopPropagation();
                        }}
                        onMouseDown={(e) => {
                            e.stopPropagation();
                        }}
                    />
                ) : (
                    <Button
                        style={{
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                            padding: '0 8px',
                            justifyContent: 'flex-start',
                        }}
                        block
                        type='text'
                    >
                        {label}
                    </Button>
                )
            }
        </div>
        <div style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            gap: 2,
        }} >
            {
                editing ? <>
                    <Button
                        title='保存'
                        icon={<SaveOutlined />}
                        type='text'
                        onMouseDown={(e) => {
                            e.stopPropagation();
                            setEditing(false)
                            onOk(newLabel)
                        }}
                    />
                    <Button
                        title='取消'
                        icon={<CloseCircleOutlined />}
                        type='text'
                        onMouseDown={(e) => {
                            e.stopPropagation();
                            setEditing(false)
                        }}
                    />
                </> : <>
                    <Button
                        title='编辑'
                        icon={<EditOutlined />}
                        type='text'
                        onClick={(e) => {
                            e.stopPropagation();
                            setEditing(true)
                        }}
                        onMouseDown={(e) => {
                            e.stopPropagation();
                        }}
                    />
                    <Button
                        title='删除'
                        icon={<DeleteOutlined />}
                        type='text'
                        onClick={(e) => {
                            e.stopPropagation();
                            onDelete()
                        }}
                        onMouseDown={(e) => {
                            e.stopPropagation();
                        }}
                    />
                </>
            }
        </div>
    </div>
}

// 添加目标
function TargetAdder(props: any) {
    const { onClick } = props
    const [value, setValue] = useState<string | undefined>();

    return < div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        gap: 2,
    }
    }>
        <Input
            placeholder="请输入"
            value={value}
            onChange={(e) => {
                setValue(e.target.value)
            }}
            onMouseDown={(e) => {
                e.stopPropagation();
            }}
            style={{ flex: 1 }}
        />
        <Button
            type="text"
            icon={<PlusOutlined />}
            onClick={(e) => {
                e.stopPropagation();
                if (!value) return
                onClick(value)
                setValue(undefined)
            }}
            onMouseDown={(e) => {
                e.stopPropagation();
            }}
        />
    </div >
}

// 表单
function EditorPanel({ onUnExpanded }: any) {

    const dispatch = useDispatch()
    const cmdInputRef = useRef<HTMLDivElement>(null)

    const player = useSelector((state: State) => state.player)
    const status = useSelector((state: State) => state.status)
    const selectedIndex = useSelector((state: State) => state.editor.editing.meta.selectedIndex)
    const commands = useSelector((state: State) => state.editor.editing.commands);// 树结构

    const selectedCommand = commands[selectedIndex]

    const isCmdEditable = player.status === PLAYER_STATUS.STOPPED
    const editable = isCmdEditable

    const [state, setState] = useState<any>({})
    const [targetOpen, setTargetOpen] = useState(false)
    const isInspecting = status === APP_STATUS.INSPECTOR

    const isSelectEnabled = canCommandSelect(selectedCommand?.cmd)
    const isFindEnabled = canCommandFind(selectedCommand?.cmd)

    const shouldUseSelectInputForTarget = doesCommandSupportTargetOptions(selectedCommand?.cmd)
    const shouldUseTextareaForTarget = ['executeScript', 'executeScript_Sandbox'].indexOf(selectedCommand?.cmd || '') !== -1
    const shouldUseNormalInputForTarget = !shouldUseSelectInputForTarget && !shouldUseTextareaForTarget

    const onDetailChange = (key: string, value: any) => {
        dispatch(updateSelectedCommand({ [key]: value }))
    }

    const onToggleSelect = () => {

        if (status === APP_STATUS.INSPECTOR) {
            dispatch(stopInspecting() as any)
        } else {
            dispatch(startInspecting() as any)
        }

        // const defaultAction = () => {
        //     if (status === APP_STATUS.INSPECTOR) {
        //         dispatch(stopInspecting())
        //     } else {
        //         dispatch(startInspecting())
        //     }

        // }
        // const takeImage = () => {
        //     return waitBeforeScreenCapture().then(() => {
        //         return askBg('PANEL_SELECT_AREA_ON_CURRENT_PAGE')
        //     })
        //         .then(res => this.props.renameVisionImage(res.fileName))
        //         .then(resolve, reject)
    }

    const handleHeightDom = () => {
        return askBg('PANEL_HIGHLIGHT_DOM', {
            lastOperation: '',
            locator: selectedCommand.target,
            cmd: selectedCommand.cmd
        })
    }

    const selectedCmdIsVisualSearch = false;// 是否使用图像库

    const [form] = useForm();

    useEffect(() => {
        form.setFieldsValue({
            command: selectedCommand?.cmd,
            target: selectedCommand?.target,
            value: selectedCommand?.value,
            description: selectedCommand?.description,
        });
    }, [selectedCommand])



    return (
        <div className='editor-panel'>
            <div className="editor-panel-header">
                <h4 className="editor-panel-title">编辑</h4>
                <Button
                    title="收起"
                    type='text'
                    size="small"
                    onClick={onUnExpanded}
                    icon={<RightOutlined />}
                    className='right-sidebar-toggle'
                />
            </div>
            <Form
                form={form}
                layout="horizontal" className="editor-panel-form" labelCol={{ span: 3 }} wrapperCol={{ span: 10 }}>
                <Form.Item label="命令" name="command" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
                    <div className="flex-row" ref={cmdInputRef}>
                        <Select
                            showSearch
                            optionFilterProp="children"
                            placeholder="command"
                            disabled={!isCmdEditable}
                            value={selectedCommand?.cmd}
                            onChange={(value) => onDetailChange('cmd', value)}
                            onKeyDown={(e) => {
                                const input = cmdInputRef.current?.querySelector('input')
                                if (/^[a-zA-Z0-9]$/.test(e.key)) {
                                    setState({ userInputCmdValue: input?.value + e.key })
                                }
                            }}
                            onBlur={() => {
                                let value = state.userInputCmdValue
                                if (value && value.length > 0) {
                                    const command = availableCommands.find(cmd => cmd.toLowerCase() === value.trim().toLowerCase())
                                    if (command) {
                                        onDetailChange('cmd', command)
                                    }
                                }
                                setState({ userInputCmdValue: '' })
                            }}
                            filterOption={(input, { key }: any) => key.toLowerCase().indexOf(input.toLowerCase()) !== -1}
                            style={{ flex: 1 }}
                            size={"default" as any}
                        >
                            {availableCommands.map(cmd => (
                                <Select.Option value={cmd} key={cmd}>
                                    {commandText(cmd)}
                                </Select.Option>
                            ))}
                        </Select>
                    </div>
                </Form.Item >
                {/* <Form.Item label='注释' name='comment' labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
                    <Button
                        style={{ padding: '0 10px' }}
                        title="Toggle comment"
                        disabled={!isCmdEditable}
                        onClick={() => {
                            dispatch(toggleCommentOnSelectedCommand() as any)
                        }}
                    >
                                //
                    </Button>
                </Form.Item> */}
                <Form.Item label="目标" name="target" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
                    <div className="flex-col">
                        {shouldUseNormalInputForTarget ? (
                            <Input
                                style={{ flex: 1, maxWidth: '100%', marginRight: '10px' }}
                                placeholder="目标"
                                disabled={!isCmdEditable}
                                value={selectedCommand?.target}
                                onChange={(e) => onDetailChange('target', e.target.value)}
                                size={"default" as any}
                            />
                        ) : null}
                        {shouldUseSelectInputForTarget ? (
                            <Select
                                disabled={!isCmdEditable}
                                value={selectedCommand?.target}
                                options={selectedCommand?.targetOptions?.map(item => ({
                                    label: item,
                                    value: item
                                })
                                ) || []}
                                onChange={(val) => onDetailChange('target', val)}
                                optionRender={(option, { index }) => {
                                    return (<OptionEditor
                                        key={option.key}
                                        label={option.label}
                                        onOk={(value: string) => {
                                            console.log('newLabel value', value)
                                            const targetOptions = [...selectedCommand?.targetOptions || []]
                                            targetOptions.splice(index, 1, value)
                                            onDetailChange('targetOptions', targetOptions)
                                        }}
                                        onDelete={() => {
                                            const targetOptions = [...selectedCommand?.targetOptions || []]
                                            targetOptions.splice(index, 1)
                                            onDetailChange('targetOptions', targetOptions)
                                        }}
                                    />)
                                }}
                                popupRender={(menu) => {
                                    return <div>
                                        {menu}
                                        <Divider style={{ margin: '8px 0' }} />
                                        <TargetAdder
                                            onClick={(value: string) => {
                                                const targetOptions = [...selectedCommand?.targetOptions || [], value]
                                                onDetailChange('targetOptions', targetOptions)
                                            }}
                                        />
                                    </div>
                                }}
                            />
                        ) : null}
                        {shouldUseTextareaForTarget ? (
                            <div className="textarea-wrapper">
                                <Input.TextArea
                                    rows={2}
                                    placeholder="target"
                                    disabled={!isCmdEditable}
                                    value={selectedCommand?.target}
                                    onChange={(e) => onDetailChange('target', e.target.value)}
                                    size={"default" as any}
                                />
                                <DoubleRightOutlined
                                    type="arrows-alt"
                                    className="open-full-editor"
                                    title="Open full editor"
                                    onClick={() => {
                                        setState({
                                            targetEditor: {
                                                visible: true,
                                                text: selectedCommand?.target
                                            }
                                        })
                                    }}
                                />
                            </div>
                        ) : null}
                        <Space style={{ marginTop: 8 }}>
                            <Button
                                disabled={!isCmdEditable || !isSelectEnabled}
                                onClick={onToggleSelect}
                            >
                                {isInspecting
                                    ? (<span>{(selectedCmdIsVisualSearch ? '👁' : '') + '取消'}</span>)
                                    : (<span>{(selectedCmdIsVisualSearch ? '👁' : '') + '捕获元素'}</span>)
                                }
                            </Button>
                            <Button
                                disabled={!editable || !isFindEnabled}
                                onClick={handleHeightDom}
                            >
                                {(selectedCmdIsVisualSearch ? '👁' : '') + '高亮元素'}
                            </Button>
                        </Space>
                    </div>
                </Form.Item>
                <Form.Item label="值" name="value" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
                    <Input
                        disabled={!isCmdEditable}
                        value={selectedCommand?.value}
                        onChange={(e) => onDetailChange('value', e.target.value)}
                        style={{ width: '100%' }}
                        placeholder="值"
                        size={"default" as any}
                    />
                </Form.Item>
                <Form.Item label="描述" name="description" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
                    <Input
                        disabled={!isCmdEditable}
                        value={selectedCommand?.description}
                        onChange={(e) => onDetailChange('description', e.target.value)}
                        style={{ width: '100%' }}
                        placeholder="描述"
                        size={"default" as any}
                    />
                </Form.Item>
            </Form>
        </div>
    );
}